package cn.stylefeng.guns.modular.weixin.controller;

import me.chanjar.weixin.mp.api.*;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.apache.commons.lang3.*;
import me.chanjar.weixin.mp.bean.message.*;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping({ "/wxmp/portal/{appid}" })
public class WxMpPortalController
{
    private final Logger logger;
    private WxMpService wxService;
    private WxMpMessageRouter messageRouter;
    
    @Autowired
    public WxMpPortalController(final WxMpService wxService, final WxMpMessageRouter messageRouter) {
        this.logger = LoggerFactory.getLogger((Class)this.getClass());
        this.wxService = wxService;
        this.messageRouter = messageRouter;
    }
    
    @GetMapping(produces = { "text/plain;charset=utf-8" })
    public String authGet(@PathVariable final String appid, @RequestParam(name = "signature", required = false) final String signature, @RequestParam(name = "timestamp", required = false) final String timestamp, @RequestParam(name = "nonce", required = false) final String nonce, @RequestParam(name = "echostr", required = false) final String echostr) {
        this.logger.info("\n\u63a5\u6536\u5230\u6765\u81ea\u5fae\u4fe1\u670d\u52a1\u5668\u7684\u8ba4\u8bc1\u6d88\u606f\uff1a[{}, {}, {}, {}]", new Object[] { signature, timestamp, nonce, echostr });
        if (StringUtils.isAnyBlank(new CharSequence[] { signature, timestamp, nonce, echostr })) {
            throw new IllegalArgumentException("\u8bf7\u6c42\u53c2\u6570\u975e\u6cd5\uff0c\u8bf7\u6838\u5b9e!");
        }
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("\u672a\u627e\u5230\u5bf9\u5e94appid=[%s]\u7684\u914d\u7f6e\uff0c\u8bf7\u6838\u5b9e\uff01", appid));
        }
        if (this.wxService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return "\u975e\u6cd5\u8bf7\u6c42";
    }
    
    @PostMapping(produces = { "application/xml; charset=UTF-8" })
    public String post(@PathVariable final String appid, @RequestBody final String requestBody, @RequestParam("signature") final String signature, @RequestParam("timestamp") final String timestamp, @RequestParam("nonce") final String nonce, @RequestParam("openid") final String openid, @RequestParam(name = "encrypt_type", required = false) final String encType, @RequestParam(name = "msg_signature", required = false) final String msgSignature) {
        this.logger.info("\n\u63a5\u6536\u5fae\u4fe1\u8bf7\u6c42\uff1a[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ", new Object[] { openid, signature, encType, msgSignature, timestamp, nonce, StringUtils.deleteWhitespace(requestBody) });
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("\u672a\u627e\u5230\u5bf9\u5e94appid=[%s]\u7684\u914d\u7f6e\uff0c\u8bf7\u6838\u5b9e\uff01", appid));
        }
        if (!this.wxService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("\u975e\u6cd5\u8bf7\u6c42\uff0c\u53ef\u80fd\u5c5e\u4e8e\u4f2a\u9020\u7684\u8bf7\u6c42\uff01");
        }
        String out = null;
        if (encType == null) {
            final WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            final WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }
            out = outMessage.toXml();
        }
        else if ("aes".equalsIgnoreCase(encType)) {
            final WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, this.wxService.getWxMpConfigStorage(), timestamp, nonce, msgSignature);
            this.logger.debug("\n\u6d88\u606f\u89e3\u5bc6\u540e\u5185\u5bb9\u4e3a\uff1a\n{} ", inMessage.toString());
            final WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }
            out = outMessage.toEncryptedXml(this.wxService.getWxMpConfigStorage());
        }
        this.logger.debug("\n\u7ec4\u88c5\u56de\u590d\u4fe1\u606f\uff1a{}", out);
        return out;
    }
    
    private WxMpXmlOutMessage route(final WxMpXmlMessage message) {
        try {
            return this.messageRouter.route(message);
        }
        catch (Exception e) {
            this.logger.error("\u8def\u7531\u6d88\u606f\u65f6\u51fa\u73b0\u5f02\u5e38\uff01", (Throwable)e);
            return null;
        }
    }
}
